const Router = require('koa-router')
const fuzzyquerygoods = new Router()
//！拿到前端的数据
//数据库连接池
const pg = require('pg');
let psql = new pg.Pool({
  database: 'running',
  user: 'run',
  port: 5432,
  host: '82.157.94.115',
  password: 'z12345678',
  max: 2
})

fuzzyquerygoods.post('/fuzzyquerygoods', async ctx => {
  // console.log(ctx.request.body);

  let { key, searchType } = ctx.request.body
  console.log(key);
  console.log(searchType);
  if (searchType == 'goods_name') {

    let searchContentPostgresql = `SELECT * FROM goods WHERE goods_name LIKE '${key}%'`;
    let content = await psql.query(searchContentPostgresql);
    if (content.rowCount > 0) {
      var fuzzyquerygoodsObj = [];
      for (var i = 0; i < content.rowCount; i++) {
        var obj = {
          goods_id: content.rows[i].goods_id,
          goods_name: content.rows[i].goods_name,
          goods_title: content.rows[i].goods_title,
          goods_price: content.rows[i].goods_price,
          goods_img: content.rows[i].goods_img
        }

        fuzzyquerygoodsObj.push(obj);
      }

      ctx.body = {
        fuzzyquerygoodsObj
      };
    }

  } else {
    let searchContentPostgresql = `SELECT * FROM goods WHERE goods_title LIKE '${key}%'`;
    let content = await psql.query(searchContentPostgresql);
    if (content.rowCount > 0) {
      var fuzzyquerygoodsObj = [];
      for (var i = 0; i < content.rowCount; i++) {
        var obj = {
          goods_id: content.rows[i].goods_id,
          goods_name: content.rows[i].goods_name,
          goods_title: content.rows[i].goods_title,
          goods_price: content.rows[i].goods_price,
          goods_img: content.rows[i].goods_img
        }

        fuzzyquerygoodsObj.push(obj);
      }

      ctx.body = {
        fuzzyquerygoodsObj
      };
    }


  }

})

module.exports = fuzzyquerygoods